package com.xyf.sys.controller;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xyf.sys.config.MiniprogramConfig;
import com.xyf.sys.constant.CommonConstant;
import com.xyf.sys.domain.ChannelConfig;
import com.xyf.sys.domain.Delivery;
import com.xyf.sys.domain.SysDownloadTask;
import com.xyf.sys.enums.DeliveryEnum;
import com.xyf.sys.service.*;
import com.xyf.sys.util.R;
import com.xyf.sys.util.WechatHttpUtil;
import com.xyf.sys.vo.DataScopeVo;
import com.xyf.sys.vo.OrderVo;
import com.xyf.sys.vo.PaymentRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author R-H
 * @Date 2024/2/181137
 * @Description
 */
@RestController
@RequestMapping("/common")
@Slf4j
@Api(tags = "通用接口")
public class CommonController {

    @Autowired
    private IDeliveryService deliveryService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private ISysPriceSchemeService priceSchemeService;
    @Autowired
    private IDictDataService dictDataService;
    @Autowired
    private IWechatService wechatService;
    @Autowired
    @Qualifier(value = "clientConfig")
    private MiniprogramConfig.MiniConfig clientConfig;
    @Autowired
    @Qualifier(value = "manageConfig")
    private MiniprogramConfig.MiniConfig manageConfig;
    @Autowired
    private IBaiduCloudService baiduCloudService;
    @Autowired
    private IRegionService regionService;
    @Autowired
    private ITencentCloudService tencentCloudService;
    @Autowired
    private IDownloadTaskService taskService;
    @Autowired
    private IOrderProductCodeService orderProductCodeService;
    @Autowired
    private IUserService userService;


    @ApiOperation("根据字典key 查询字典列表")
    @GetMapping("/list")
    public Object list(@ApiParam(value = "dictKey", allowableValues = "dicts_delivery,dicts_roles,dicts_permi,dicts_logisticPricescheme,dicts_dryCleaningPricescheme,dicts_product_category") @RequestParam String dictKey) {
        if (StringUtils.isBlank(dictKey)) {
            return R.ok();
        }
        if ("dicts_delivery".equalsIgnoreCase(dictKey)) {
            return R.ok(deliveryService.getList());
        }
        if ("dicts_roles".equalsIgnoreCase(dictKey)) {
            return R.ok(roleService.getAllRoleList());
        }
        if ("dicts_permi".equalsIgnoreCase(dictKey)) {
            return R.ok();
        }
        if ("dicts_logisticPricescheme".equalsIgnoreCase(dictKey)) {
            return R.ok(priceSchemeService.getList(1));
        }
        if ("dicts_dryCleaningPricescheme".equalsIgnoreCase(dictKey)) {
            return R.ok(priceSchemeService.getList(2));
        }
        if ("dicts_product_category".equalsIgnoreCase(dictKey)) {
            return R.ok(dictDataService.list("sys_product_category_type"));
        }
        if ("dicts_product_service".equalsIgnoreCase(dictKey)) {
            return R.ok(dictDataService.list("sys_product_service"));
        }
        return R.ok();
    }

    @ApiOperation("文本OCR")
    @PostMapping("/textOCR")
    public R textOCR(@RequestBody Map<String, String> body, HttpServletRequest request) throws Exception {
        String appid = request.getHeader("APPID");
        String imgUrl = body.get("imgUrl");
        String text = body.get("text");
        if (StringUtils.isBlank(text)) {
//            String secret = appid.equals(clientConfig.getAppid()) ? clientConfig.getSecret() : manageConfig.getSecret();
            JSONArray items = wechatService.textOCR(manageConfig.getAppid(), manageConfig.getSecret(), imgUrl);
            StringBuffer textBuffer = new StringBuffer();
            for (int i = 0; i < items.size(); i++) {
                JSONObject item = items.getJSONObject(i);
                textBuffer.append(item.getString("text"));
            }
            text = textBuffer.toString();
        }
        return R.ok(baiduCloudService.textToAddress(text));
    }

    @ApiOperation("身份证识别")
    @PostMapping("/idCardOCR")
    public R idCardOCR(@RequestBody Map<String, String> body, HttpServletRequest request) throws Exception {
        String appid = request.getHeader("APPID");
        String imgUrl = body.get("imgUrl");
        return R.ok(wechatService.idCardOCR(appid, appid.equals(clientConfig.getAppid()) ? clientConfig.getSecret() : manageConfig.getSecret(), imgUrl));
    }


    @ApiOperation("查询城市列表")
    @GetMapping("/region")
    public Object region() {
        return R.ok(regionService.regionList());
    }


    @ApiOperation("上传文件")
    @PostMapping("/upload")
    public Object upload(@RequestParam("file") MultipartFile multipartFile) {
        // 获取用户临时目录
        try {
            Path tempDir = Paths.get(System.getProperty("java.io.tmpdir"));
            // 获取原始文件名
            String originalFileName = multipartFile.getOriginalFilename();
            // 生成规律文件名，例如在原文件名前添加时间戳
            String timeStamp = String.valueOf(System.currentTimeMillis());
            String fileName = timeStamp + "_" + originalFileName;
            // 构建完整的文件路径
            Path tempFilePath = tempDir.resolve(fileName);
            // 将MultipartFile的内容写入临时文件
            Files.copy(multipartFile.getInputStream(), tempFilePath, StandardCopyOption.REPLACE_EXISTING);
            File file = tempFilePath.toFile();
            String url = tencentCloudService.upload(file.getAbsolutePath());
            return R.ok(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.fail("上传失败");
    }

    @ApiOperation("任务列表")
    @PostMapping("/taskList")
    public R taskList(@RequestBody PaymentRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<SysDownloadTask> list = taskService.list(request.getDeptId());
        return R.ok(new PageInfo<>(list));
    }

    @ApiOperation("批量生成订单码")
    @GetMapping("/batchGenerateCode")
    public R batchGenerateCode(@RequestParam Integer batchNumber, @RequestParam String regimentId, HttpServletRequest request) {
        return R.ok(orderProductCodeService.batchGenerate(batchNumber, regimentId, request.getHeader("openid")));
    }

    @ApiOperation("极兔切换")
    @PostMapping("/jtsd")
    public R jtsd(@RequestBody Map<String, Object> body, HttpServletRequest request) {
        Delivery config = deliveryService.getConfig(DeliveryEnum.JTSD.toString());
        if (body.get("expressType").toString().equalsIgnoreCase("1")) {
            config.setAuthCode("EZ");
        }
        if (body.get("expressType").toString().equalsIgnoreCase("2")) {
            config.setAuthCode("TYD");
        }
        config.setUpdateTime(new Date());
        config.setUpdateBy(request.getHeader("openid"));
        deliveryService.update(config);
        return R.ok();
    }

    @ApiOperation("设置角色数据权限")
    @PostMapping("/dataScope")
    public R dataScope(@RequestBody DataScopeVo body, HttpServletRequest request) {
        return R.ok(roleService.authDataScope(body.getRoleId(), body.getDeptIds()));
    }

    @ApiOperation("获取客户端程序短链")
    @PostMapping("/getShortLink")
    public R getShortLink(@RequestBody Map<String, String> body, HttpServletRequest request) {
        String accessToken = wechatService.getAccessToken(clientConfig.getAppid(), clientConfig.getSecret());
        return R.ok(wechatService.generateShortLink(body.get("pageUrl"), body.get("pageTitle"), body.get("isPermanent"), accessToken));
    }

    @ApiOperation("消息跳转路径设置接口")
    @PostMapping("/setJumpPath")
    public R setJumpPath(Map<String, String> body, HttpServletRequest request) {
        String accessToken = wechatService.getAccessToken(clientConfig.getAppid(), clientConfig.getSecret());
        return R.ok(wechatService.setJumpPath(body.get("path"), accessToken));
    }
}
